import React, { Component } from 'react';
import {
    View,
    Image,
    TextInput,
    TouchableHighlight,
    StyleSheet,
    Platform,
    Dimensions
} from 'react-native';

import PropTypes from "prop-types";
import Color from "../../config/theme/standard/color"
import FontSize from "../../config/theme/standard/fonts"
import Label from '../label';

export default class TextArea extends Component {

    constructor(props) {
        super(props);
        this.maxNumber = this.props.type == 'auto' ? 100 : undefined;
        this.inputHeight = this.props.type == 'auto' ? 21 : 21 + (this.props.rows - 1) * 18;
        this.inputContainerHeight = 24
        this.state = {
            prevPropsDefaultValue: this.props.defaultValue,
            text: this.props.defaultValue ? this.props.defaultValue : '',
            height: this.inputHeight,
            containerHeight: this.inputContainerHeight,
            showClear: false,
            info: '',
            errorInfo: ''
        };
        this.textInputHeight = null
        this.key = ''
        this.number = 0
        this.isEnterCount = 0 //统计是否按下换行符
        this.aimHeight = 0    //计算允许高度
    }

    _onChange(text) {
        // console.log(text, '_onChange--');

        // if (this.isLimit) return
        // 检测是否为web并且键盘类型为纯数字键盘
        if (Platform.OS === 'web' && this.props.keyboardType === 'numeric') {
            if (this.props.maxLength) {
                if (text.length > this.props.maxLength) {

                    text = text.slice(0, this.props.maxLength);
                }
            }
        }
        
        this.setState({
            text: text,
            info: '',
            errorInfo: '',
        });
        if (typeof (this.props.onChange) === 'function') {
            this.props.onChange(text);
        }
        // 当文本为空，清除各种条件
        if (text.length == 0) {
            this.reset()
        }

    }
    reset() {
        this.number = 0
        this.isEnterCount = 0
        this.textInputHeight = 0
    }
    onBlur() {
        this.setState({
            showClear: false,
        });
        if (this.props.onBlur) {
            this.props.onBlur();
        }
    }

    onWebBlur() {
        this.setState({
            showClear: false,
        });
        if (this.props.onBlur) {
            this.props.onBlur();
        }
        if (this.props.showErrorInfo && this.props.minLength > this.state.text.length) {
            this.setState({ errorInfo: this.props.errorInfo })
        } else {
            this.setState({ info: this.props.info });
        }
    }

    onFocus() {
        this.setState({
            showClear: true,
            info: '',
            errorInfo: '',
            containerHeight: 24,
        });
        if (this.props.onFocus) {
            this.props.onFocus();
        }
    }

    //输入字符数小于给定最小字符数时，展示错误信息
    _onEndEditing() {
        if (this.props.showErrorInfo && this.props.minLength > this.state.text.length) {
            this.setState({ errorInfo: this.props.errorInfo })
            if(this.props.type == 'auto') {
                this.setState({containerHeight: 47})
            }
        } else {
            this.setState({ info: this.props.info });
        }
    }

    _onContentSizeChange(event) {

        if (this.props.type == 'auto') {
            let height = event.nativeEvent.contentSize.height < 21 ? 21 : event.nativeEvent.contentSize.height;

            this.setState({
                height: height,
            });
        }

        if (typeof (this.props.onContentSizeChange) === 'function') {
            this.props.onContentSizeChange(event);
        }
    };

    static getDerivedStateFromProps(nextProps, prevState) {
        if (('defaultValue' in nextProps) && (nextProps.defaultValue !== prevState.prevPropsDefaultValue)) {
            return {
                prevPropsDefaultValue: nextProps.defaultValue,
                text: nextProps.defaultValue,
            };
        }
        return null;
    }
    componentDidMount(){
        // 监听屏幕宽度变化
        this.dimensionsListener = Dimensions.addEventListener('change', ()=>{
            this.forceUpdate();
        });
    }
    componentWillUnmount(){
        // 移除监听
        this.dimensionsListener && this.dimensionsListener.remove();
        
      }
    onKeyPress(e) {
        let key = e.nativeEvent.key

        // 记录当前按下的key值
        if (this.key !== key) {
            this.key = key
        }
        // 记录按下换行的次数
        if (key == "Enter") {
            this.isEnterCount++
        }
     
    }
    render() {
        const {
            title,
            type,
            style,
            rows,
            maxLength,
            minLength,
            showClearIcon,
            editable,
            showCount,
            showErrorInfo,
            multilineFlag,
            keyboardType,
            hasTopBorder,
            hasBottomBorder,
            isMerge,
            titleWidth,
            isRequired,
            inputContainerStyle
        } = this.props;

        let { errorInfo, info } = this.state;

        const containerStyles = [styles.container];
        const imageContainerStyles = [styles.imageContainer, Platform.OS == 'harmony' &&{ zIndex:1 }];
        const inputStyles = [styles.input];
        const dividerStyles = [styles.divider];
        const titleStyles = [styles.titleContainer];
        containerStyles.push({ height: this.state.height +  this.state.containerHeight });

        if (titleWidth) {
            titleStyles.push({ width: titleWidth });
        }

        if(type == 'normal') {
            containerStyles.push({ paddingLeft: 15 });
            containerStyles.push({ width: Dimensions.get('window').width});
            containerStyles.push({ backgroundColor: Color.white });
        }

        let countItem = null;
        let titleItem = null;
        let clearItem = null;

        if (maxLength > 0) {
            this.maxNumber = maxLength;
        }

        let titleCon = [styles.labelContainer];
        if (isRequired) {
            titleCon.push({ justifyContent: 'flex-start', flexDirection: 'row' });
        }

        if (type == 'normal') {
            inputStyles.push({ fontSize: FontSize.textArea.inputFontSize});
            if (showCount && this.maxNumber > 0) {
                let count = this.state.text.length + '/' + this.maxNumber;
                containerStyles.push({paddingRight: 15,  paddingBottom: 34, height: this.state.height + 46 });
                countItem = <View style={[styles.count, Platform.OS == 'harmony' &&{ zIndex:1 }]}>
                    <Label text={count} labelStyle={{color:Color.textArea.count,fontSize:FontSize.textArea.countFontSize,fontWeight:'400',textAlign:'right'}}/>
                </View>;
            }
        } else {
            titleItem =
                <TouchableHighlight
                    style={titleStyles}
                    underlayColor='transparent'>
                    <View style={titleCon}>
                        <Label text={title} labelStyle={{color:Color.textArea.title,fontSize:FontSize.textArea.titleFontSize,fontWeight:'400'}}/>
                        {isRequired ? <Image
                            source={require('../../assets/textArea_star.png')}
                            style={{ height: 8, width: 8, resizeMode: 'contain', marginLeft: 5, marginTop: 6 }} /> : null}
                    </View>
                </TouchableHighlight>;
        }

        if (showClearIcon && this.state.showClear && this.state.text.length > 0 && type == 'auto') {
            containerStyles.push({ paddingRight: 44 });
            clearItem = (
                <TouchableHighlight
                    onPress={() => {
                        this._onChange('');
                    }}
                    style={imageContainerStyles}
                    underlayColor='transparent'>
                    <Image
                        source={require('../../assets/icon_textArea_clear.png')}
                        style={styles.image} />
                </TouchableHighlight>
            );
        }

        if (hasTopBorder) {
            containerStyles.push({ borderTopWidth: 1 });
        }

        if (hasBottomBorder) {
            containerStyles.push({ borderBottomWidth: 1 });
        }

        if (isMerge) {
            dividerStyles.push({ width: Dimensions.get('window').width - 15, marginLeft: 15 });
        } else {
            dividerStyles.push({ height: 0 });
        }

        let returnInfo;
        const errorInfoStyles = [styles.errorInfo, Platform.OS == 'harmony' &&{ zIndex:1 }];
        if (showErrorInfo && this.props.type == 'normal') {
            errorInfoStyles.push({right: 74})
        } else if (showErrorInfo && this.props.type == 'auto') {
            errorInfoStyles.push({left: 125})
        }
        if (showErrorInfo) {
            returnInfo = (
                <View style={showCount ? errorInfoStyles : [errorInfoStyles, { right: 15 }]}>
                    <Label text={errorInfo}  labelStyle={{color:Color.textArea.errorInfo,fontSize:FontSize.textArea.errorFontSize,fontWeight:'400'}}/>
                </View>
            );
        } else {
            returnInfo = (
                <View style={showCount ? errorInfoStyles : [errorInfoStyles, { right: 15 }]}>
                    <Label text={info}  labelStyle={{color:Color.textArea.errorInfo,fontSize:FontSize.textArea.errorFontSize,fontWeight:'400'}}/>
                </View>
            );
        }

        if (!editable && this.state.text.length != 0) {
            inputStyles.push({ textAlign: 'left', color: Color.textArea.disable });
        }
  
        return (
            <View>
                <View style={containerStyles}>
                    {titleItem}
                    <View style={[styles.inputContainer, inputContainerStyle]} ref='textView'>
                        <TextInput
                            ref="textInput"
                            underlineColorAndroid="transparent"
                            style={[inputStyles, { height: Math.max(20, this.state.height),fontSize:FontSize.textArea.inputFontSize }, style]}
                            onChangeText={(text) => this._onChange(text)}
                            onContentSizeChange={(event) => this._onContentSizeChange(event)}
                            multiline={multilineFlag}
                            numberOfLines={rows}
                            maxLength={this.maxNumber}
                            minLength={minLength}
                            editable={editable}
                            placeholder={this.props.placeholder ? this.props.placeholder : '请输入'}
                            placeholderTextColor={Color.textArea.placeholder}
                            value={this.state.text}
                            onBlur={() => { (Platform.OS == 'web') ? this.onWebBlur() : this.onBlur() }}
                            onFocus={() => this.onFocus()}
                            onEndEditing={() => this._onEndEditing()}
                            autoCorrect={false}
                            keyboardType={keyboardType}
                            blurOnSubmit={this.props.nolineChange}
                            onKeyPress={(event) => this.onKeyPress(event)}
                        />
                    </View>
                    {clearItem}
                    {returnInfo}
                    {countItem}
                </View>
                <View style={dividerStyles} />
            </View>
        );
    }
}

TextArea.propTypes = {
    title: PropTypes.string,
    type: PropTypes.oneOf(['auto', 'normal']),
    style: PropTypes.object,
    defaultValue: PropTypes.string,
    placeholder: PropTypes.string,
    rows: PropTypes.number,
    maxLength: PropTypes.number,
    minLength: PropTypes.number,
    //最小输入字数
    onChange: PropTypes.func,
    editable: PropTypes.bool,
    onContentSizeChange: PropTypes.func,
    showClearIcon: PropTypes.bool,
    showCount: PropTypes.bool,
    showErrorInfo: PropTypes.bool,
    //是否展示错误提示
    errorInfo: PropTypes.string,
    //错误提示内容
    info: PropTypes.string,
    //提示内容
    multilineFlag: PropTypes.bool,
    //是否多行输入
    //弹起键盘类型
    keyboardType: PropTypes.oneOf(['default', 'numeric', 'email-address', 'phone-pad','numbers-and-punctuation']),
    hasTopBorder: PropTypes.bool,
    hasBottomBorder: PropTypes.bool,
    isMerge: PropTypes.bool,
    titleWidth: PropTypes.number,
    //是否为必输项（显示红色*号）
    isRequired: PropTypes.bool,
    inputContainerStyle: PropTypes.any,
    //文本是否需要间隔
    noInterval: PropTypes.bool,
    //开启换行失焦并处理换行符
    nolineChange: PropTypes.bool,
};
TextArea.defaultProps = {
    type: 'auto',
    showClearIcon: false,
    editable: true,
    rows: 4,
    showCount: true,
    showErrorInfo: false,
    errorInfo: '',
    info: '',
    multilineFlag: true,
    keyboardType: "default",
    isMerge: false,
    hasTopBorder: false,
    hasBottomBorder: false,
    isRequired: false,
    nolineChange: false
};


const styles = StyleSheet.create({
    container: {
        flexDirection: 'row',
        paddingRight: 15,
        minHeight: 44,
        borderColor: Color.border,
      
    },
    inputContainer: {
        flex: 1,
        justifyContent: 'flex-start',
        paddingTop: 12,
    },
    input: {
        fontSize: FontSize.textArea.inputFontSize,
        paddingTop: 1,
        paddingBottom: 0,
        color: Color.textArea.input,
        fontWeight:'400',
        textAlignVertical: 'top',
        paddingLeft: 0
    },
    count: {
        position: 'absolute',
        right: 15,
        bottom: 12,
    },
    titleContainer: {
        width:125,
        paddingLeft: 15,
        justifyContent: 'flex-start',
        paddingTop: 12,
    },
    labelContainer: {
        justifyContent: 'center',
    },
    imageContainer: {
        position: 'absolute',
        right: 8,
        top: 8,
    },
    image: {
        width: 28,
        height: 28,
        zIndex: 10,
        resizeMode: 'contain'
    },
    errorInfo: {
        position: 'absolute',
        bottom: 12,
    },
    divider: {
        width: Dimensions.get('window').width,
        height: 1,
        backgroundColor: Color.border,
    }
});
